﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using HRMSys.DAL;
using HRMSys.Model;

namespace HRMSys.UI.SystemMgr
{
    /// <summary>
    /// OperatorEditUI.xaml 的交互逻辑
    /// </summary>
    public partial class OperatorEditUI : Window
    {
        public bool IsInsert { get; set; }  //是否是新增的
        public Guid EditingId { get; set; } //被编辑的数据的Id

        public OperatorEditUI()
        {
            InitializeComponent();
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = false;
        }

        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            if (IsInsert == true) //如果是新增操作
            {
                Operator op = new Operator();
                op.UserName = txtUserName.Text;
                op.Password = CommonHelper.GetMD5(pbPwd.Password + CommonHelper.GetMD5Salt());
                op.RealName = txtRealName.Text;

                OperatorDAL dal = new OperatorDAL();
                int result = dal.Insert(op);

                MessageBox.Show(result == 1 ? "添加成功" : "添加失败!");

                DialogResult = true;
            }
            else //如果是编辑操作,
            {
                string password = pbPwd.Password;

                OperatorDAL dal = new OperatorDAL();
                int result;

                if (password.Length <= 0) //代表用户不修改密码
                {
                    result = dal.Update(txtUserName.Text, txtRealName.Text, EditingId);

                }
                else
                {
                    result = dal.Update(txtUserName.Text, txtRealName.Text, pbPwd.Password, EditingId);
                }

                MessageBox.Show(result == 1 ? "修改成功" : "修改失败");
                DialogResult = true;
            }
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            if (IsInsert == true)
            {
                //如果是新增, 暂时不做任何操作.
            }
            else //如果是删除操作
            {
                OperatorDAL dal = new OperatorDAL();
                Operator op = dal.GetById(EditingId);
                txtUserName.Text = op.UserName;
                txtRealName.Text = op.RealName;
            }
        }
    }
}
